package com.hbt.en_rem_hou.controller;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

@Controller
public class MyController {
    @RequestMapping("/toLogin")
    public String toLogin(){
        System.out.println("tologin");
        return "index";
    }

    @RequestMapping("/trans/{src}")
    @ResponseBody
    public String getTrans(@PathVariable("src") String src){
        System.out.println("进入 trans Controller");
        try
        {
            URL url = new URL("http://fanyi.youdao.com/translate?&doctype=json&type=AUTO&i="+src);
            URLConnection urlConnection = url.openConnection();
            HttpURLConnection connection = null;
            if(urlConnection instanceof HttpURLConnection)
            {
                connection = (HttpURLConnection) urlConnection;
            }
            else
            {
                System.out.println("请输入 URL 地址");
                return "";
            }
            BufferedReader in = new BufferedReader(
                    new InputStreamReader(connection.getInputStream()));
            String urlString = "";
            String current;
            while((current = in.readLine()) != null)
            {
                urlString += current;
            }
            JSONObject object = JSONObject.fromString(urlString);
            JSONArray array = (JSONArray) object.getJSONArray("translateResult").get(0);
            JSONObject jsonObject = (JSONObject)array.get(0);
            System.out.println("结果:"+jsonObject.getString("tgt"));
            return jsonObject.getString("tgt");
        }catch(IOException e)
        {
            e.printStackTrace();
            return "null";
        }
    }
}
